package com.xuhao.examai.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.xuhao.examai.common.ResultVO;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * 处理业务异常
	 */
	@ExceptionHandler(BusinessException.class)
	public ResultVO<Object> handleBusinessException(BusinessException e) {
		log.warn("业务异常: {}", e.getMessage());
		return ResultVO.error(e.getCode(), e.getMessage());
	}

	/**
	 * 处理Spring Security认证异常
	 */
	@ExceptionHandler({ BadCredentialsException.class, AuthenticationException.class })
	public ResultVO<Object> handleAuthenticationException(AuthenticationException e) {
		log.warn("认证异常: {}", e.getMessage());
		return ResultVO.unauthorized("用户名或密码错误");
	}

	/**
	 * 处理数据验证异常
	 */
	@ExceptionHandler({ MethodArgumentNotValidException.class, BindException.class })
	public ResultVO<Object> handleValidationException(Exception e) {
		log.warn("数据验证异常: {}", e.getMessage());
		return ResultVO.error(400, "数据验证失败");
	}

	/**
	 * 处理通用异常
	 */
	@ExceptionHandler(Exception.class)
	public ResultVO<Object> handleException(Exception e) {
		log.error("系统异常: ", e);
		return ResultVO.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误");
	}
}
